package com.amon.amonplayer;

import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.MessageQueue;
import android.util.Log;

import androidx.annotation.RequiresApi;

import java.lang.reflect.Field;
import java.util.List;
import java.util.concurrent.AbstractExecutorService;
import java.util.concurrent.TimeUnit;

public class LooperExecutor extends AbstractExecutorService {

    private final Handler mHandler;

    public LooperExecutor(Looper looper) {
        mHandler = new Handler(looper);
    }

    @Override
    public void shutdown() {
        throw new UnsupportedOperationException();
    }

    @Override
    public List<Runnable> shutdownNow() {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean isShutdown() {
        return false;
    }

    @Override
    public boolean isTerminated() {
        return false;
    }

    @Override
    public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
        throw new UnsupportedOperationException("");
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void execute(Runnable command) {
        MessageQueue messageQueue = mHandler.getLooper().getQueue();
        try {
            Field field = MessageQueue.class.getDeclaredField("mMessages");
            field.setAccessible(true);
            Message message = (Message) field.get(messageQueue);
            if (message != null) {
                int i = 0;
                Field nextField = Message.class.getDeclaredField("next");
                nextField.setAccessible(true);
                for (;;) {
                    Message nextMsg = (Message) nextField.get(message);
                    if (nextMsg != null) {
                        i++;
                    } else {
                        break;
                    }
                    message = nextMsg;
                }
                Log.e("TAG", "execute:" + i);
            }
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
        mHandler.post(command);
    }
}
